package com.example.service.impl;

import com.example.common.PageResult;
import com.example.common.Result;
import com.example.dto.AdminInventoryQueryDTO;
import com.example.entity.AdminInventoryRecord;
import com.example.entity.SupplyProduct;
import com.example.mapper.AdminInventoryRecordMapper;
import com.example.mapper.SupplyProductMapper;
import com.example.service.AdminInventoryService;
import com.example.util.UserContextUtil;
import com.example.vo.AdminInventoryRecordVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 管理员库存管理Service实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminInventoryServiceImpl implements AdminInventoryService {

    private final AdminInventoryRecordMapper adminInventoryRecordMapper;
    private final SupplyProductMapper supplyProductMapper;
    private final UserContextUtil userContextUtil;

    @Override
    public Result<PageResult<AdminInventoryRecordVO>> getRecordsPage(AdminInventoryQueryDTO queryDTO) {
        try {
            PageHelper.startPage(queryDTO.getCurrent(), queryDTO.getSize());
            List<AdminInventoryRecordVO> records = adminInventoryRecordMapper.selectPageList(queryDTO);
            
            // 设置显示名称
            records.forEach(this::setDisplayNames);
            
            PageInfo<AdminInventoryRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<AdminInventoryRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setCurrent(queryDTO.getCurrent());
            pageResult.setSize(queryDTO.getSize());
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询管理员库存记录失败", e);
            return Result.error("查询失败");
        }
    }

    @Override
    public Result<List<AdminInventoryRecordVO>> getRecordsByProductId(Long productId) {
        try {
            List<AdminInventoryRecordVO> records = adminInventoryRecordMapper.selectByProductId(productId);
            records.forEach(this::setDisplayNames);
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据商品ID查询库存记录失败", e);
            return Result.error("查询失败");
        }
    }

    @Override
    public Result<PageResult<AdminInventoryRecordVO>> getInRecordsPage(AdminInventoryQueryDTO queryDTO) {
        try {
            PageHelper.startPage(queryDTO.getCurrent(), queryDTO.getSize());
            List<AdminInventoryRecordVO> records = adminInventoryRecordMapper.selectInRecords(queryDTO);
            
            records.forEach(this::setDisplayNames);
            
            PageInfo<AdminInventoryRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<AdminInventoryRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setCurrent(queryDTO.getCurrent());
            pageResult.setSize(queryDTO.getSize());
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询入库记录失败", e);
            return Result.error("查询失败");
        }
    }

    @Override
    public Result<PageResult<AdminInventoryRecordVO>> getOutRecordsPage(AdminInventoryQueryDTO queryDTO) {
        try {
            PageHelper.startPage(queryDTO.getCurrent(), queryDTO.getSize());
            List<AdminInventoryRecordVO> records = adminInventoryRecordMapper.selectOutRecords(queryDTO);
            
            records.forEach(this::setDisplayNames);
            
            PageInfo<AdminInventoryRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<AdminInventoryRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setCurrent(queryDTO.getCurrent());
            pageResult.setSize(queryDTO.getSize());
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询出库记录失败", e);
            return Result.error("查询失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> createProductInRecord(Long productId, Integer quantity, String remark) {
        try {
            SupplyProduct product = supplyProductMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }

            AdminInventoryRecord record = new AdminInventoryRecord();
            record.setRecordNo(generateRecordNo());
            record.setProductId(productId);
            record.setProductName(product.getProductName());
            record.setProductCode(product.getProductCode());
            record.setRecordType("IN");
            record.setQuantity(quantity);
            record.setBeforeStock(product.getStock() - quantity);
            record.setAfterStock(product.getStock());
            record.setUnitCost(product.getCost());
            if (product.getCost() != null) {
                record.setTotalCost(product.getCost().multiply(new BigDecimal(quantity)));
            }
            record.setOperatorId(userContextUtil.getCurrentUserId());
            record.setOperatorName(userContextUtil.getCurrentUserNickname());
            record.setBusinessType("CREATE");
            record.setRemark(remark);
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            record.setDeleted(0);

            adminInventoryRecordMapper.insert(record);
            log.info("创建商品入库记录成功，商品: {}, 数量: {}", product.getProductName(), quantity);
            
            return Result.success();
        } catch (Exception e) {
            log.error("创建商品入库记录失败", e);
            return Result.error("创建记录失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> createAllocateOutRecord(Long productId, Long targetMerchantId, Integer quantity, String remark) {
        try {
            SupplyProduct product = supplyProductMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }

            AdminInventoryRecord record = new AdminInventoryRecord();
            record.setRecordNo(generateRecordNo());
            record.setProductId(productId);
            record.setProductName(product.getProductName());
            record.setProductCode(product.getProductCode());
            record.setRecordType("OUT");
            record.setQuantity(quantity);
            record.setBeforeStock(product.getStock() + quantity);
            record.setAfterStock(product.getStock());
            record.setUnitCost(product.getCost());
            if (product.getCost() != null) {
                record.setTotalCost(product.getCost().multiply(new BigDecimal(quantity)));
            }
            record.setOperatorId(userContextUtil.getCurrentUserId());
            record.setOperatorName(userContextUtil.getCurrentUserNickname());
            record.setTargetMerchantId(targetMerchantId);
            record.setBusinessType("ALLOCATE");
            record.setRemark(remark);
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            record.setDeleted(0);

            adminInventoryRecordMapper.insert(record);
            log.info("创建商品分配出库记录成功，商品: {}, 数量: {}", product.getProductName(), quantity);
            
            return Result.success();
        } catch (Exception e) {
            log.error("创建商品分配出库记录失败", e);
            return Result.error("创建记录失败");
        }
    }

    @Override
    @Transactional
    public Result<Void> createAdjustRecord(Long productId, Integer quantity, String recordType, String remark) {
        try {
            SupplyProduct product = supplyProductMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }

            AdminInventoryRecord record = new AdminInventoryRecord();
            record.setRecordNo(generateRecordNo());
            record.setProductId(productId);
            record.setProductName(product.getProductName());
            record.setProductCode(product.getProductCode());
            record.setRecordType(recordType);
            record.setQuantity(Math.abs(quantity));
            
            if ("IN".equals(recordType)) {
                record.setBeforeStock(product.getStock() - quantity);
                record.setAfterStock(product.getStock());
            } else {
                record.setBeforeStock(product.getStock() + quantity);
                record.setAfterStock(product.getStock());
            }
            
            record.setUnitCost(product.getCost());
            if (product.getCost() != null) {
                record.setTotalCost(product.getCost().multiply(new BigDecimal(Math.abs(quantity))));
            }
            record.setOperatorId(userContextUtil.getCurrentUserId());
            record.setOperatorName(userContextUtil.getCurrentUserNickname());
            record.setBusinessType("ADJUST");
            record.setRemark(remark);
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            record.setDeleted(0);

            adminInventoryRecordMapper.insert(record);
            log.info("创建库存调整记录成功，商品: {}, 数量: {}", product.getProductName(), quantity);
            
            return Result.success();
        } catch (Exception e) {
            log.error("创建库存调整记录失败", e);
            return Result.error("创建记录失败");
        }
    }

    @Override
    public Result<List<AdminInventoryRecordVO>> exportRecords(AdminInventoryQueryDTO queryDTO) {
        try {
            List<AdminInventoryRecordVO> records = adminInventoryRecordMapper.selectPageList(queryDTO);
            records.forEach(this::setDisplayNames);
            return Result.success(records);
        } catch (Exception e) {
            log.error("导出库存记录失败", e);
            return Result.error("导出失败");
        }
    }

    @Override
    public Result<Object> getInventoryStatistics(String startTime, String endTime) {
        // TODO: 实现库存统计逻辑
        return Result.success("统计功能待实现");
    }

    /**
     * 设置显示名称
     */
    private void setDisplayNames(AdminInventoryRecordVO record) {
        // 设置操作类型显示名称
        if ("IN".equals(record.getRecordType())) {
            record.setRecordTypeName("入库");
        } else if ("OUT".equals(record.getRecordType())) {
            record.setRecordTypeName("出库");
        }

        // 设置业务类型显示名称
        switch (record.getBusinessType()) {
            case "CREATE":
                record.setBusinessTypeName("新增商品");
                break;
            case "ALLOCATE":
                record.setBusinessTypeName("分配给商家");
                break;
            case "ADJUST":
                record.setBusinessTypeName("库存调整");
                break;
            default:
                record.setBusinessTypeName(record.getBusinessType());
        }
    }

    /**
     * 生成记录编号
     */
    private String generateRecordNo() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        return "AIR" + timestamp + random;
    }
} 